package com.ushio.commonmodule.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ushio.commonmodule.pojo.user.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

public class JwtUtil {
    private static final String SECRET = "asdfghjkl_zwk";

    private static final long EXPIRATION_TIME = 1000 * 60 * 60;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 生成带完整用户信息的 JWT
    public static String generateToken(User user) {
        try {
            String userJson = objectMapper.writeValueAsString(user);
            Date now = new Date();
            Date expire = new Date(now.getTime() + EXPIRATION_TIME);

            return JWT.create()
                    .withClaim("user", userJson)
                    .withIssuedAt(now)
                    .withExpiresAt(expire)
                    .sign(Algorithm.HMAC256(SECRET));
        } catch (Exception e) {
            throw new RuntimeException("生成 JWT 时失败", e);
        }
    }

    // 验证 Token 并返回 DecodedJWT
    public static DecodedJWT verifyToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        return verifier.verify(token);
    }

    // 从 token 中解析用户名（无需验证）
    public static String getUsername(String token) {
        return JWT.decode(token).getClaim("username").asString();
    }

    // 判断 token 是否过期
    public static boolean isExpired(String token) {
        Date expiresAt = JWT.decode(token).getExpiresAt();
        return expiresAt != null && expiresAt.before(new Date());
    }

    // 解析 token 并还原成 User 对象
    public static User parseUser() {
        try {
            ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            HttpServletRequest request = attrs.getRequest();

            String token = request.getHeader("Authorization");

            if (token.startsWith("Bearer ")){
                token = token.substring(7);
            }

            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            String userJson = jwt.getClaim("user").asString();
            return objectMapper.readValue(userJson, User.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析 JWT 失败", e);
        }
    }
}
